<template>
  <div class="home">
    <div class="text-center">
      <img src="@/assets/imgs/welcome.png" class="home-bg" alt="" />
    </div>
    <div class="leaderboards">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>订单数排行榜</span>
                <el-tabs v-model="countTab" class="card-tabs" size="small">
                  <el-tab-pane label="昨日" name="yesterday" />
                  <el-tab-pane label="当月" name="month" />
                </el-tabs>
              </div>
            </template>
            <el-table
              :data="countTab === 'yesterday' ? countRanking.yesterday : countRanking.month"
              size="small"
              height="190"
              border
            >
              <el-table-column type="index" label="排名" width="70" />
              <el-table-column
                prop="name"
                label="人员/团队"
                min-width="140"
                show-overflow-tooltip
              />
              <el-table-column prop="orders" label="订单数" width="100" align="right" />
              <el-table-column label="占比" width="120" align="center">
                <template #default="{ row }">
                  <el-tooltip :content="String(row.percent)" placement="top" effect="dark">
                    <el-progress
                      :percentage="parseInt(String(row.percent))"
                      :stroke-width="10"
                      :show-text="false"
                    />
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>订单金额排行榜</span>
                <el-tabs v-model="amountTab" class="card-tabs" size="small">
                  <el-tab-pane label="昨日" name="yesterday" />
                  <el-tab-pane label="当月" name="month" />
                </el-tabs>
              </div>
            </template>
            <el-table
              :data="amountTab === 'yesterday' ? amountRanking.yesterday : amountRanking.month"
              size="small"
              height="190"
              border
            >
              <el-table-column type="index" label="排名" width="70" />
              <el-table-column
                prop="name"
                label="人员/团队"
                min-width="140"
                show-overflow-tooltip
              />
              <el-table-column prop="amountUsd" label="美元" width="140" align="right">
                <template #default="{ row }">{{ formatCurrencyUsd(row.amountUsd) }}</template>
              </el-table-column>
              <el-table-column prop="amountCny" label="人民币" width="140" align="right">
                <template #default="{ row }">{{ formatCurrencyCny(row.amountCny) }}</template>
              </el-table-column>
              <el-table-column label="占比/金额" width="140" align="center">
                <template #default="{ row }">
                  <el-tooltip :content="String(row.percent)" placement="top" effect="dark">
                    <el-progress
                      :percentage="parseInt(String(row.percent))"
                      :stroke-width="10"
                      :show-text="false"
                    />
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="todos">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>我的发起</span>
              </div>
            </template>
            <el-table :data="pagedMyInitiated" size="small" height="400">
              <el-table-column prop="create_time" label="创建时间" min-width="140" />
              <el-table-column prop="operate" label="操作类型" min-width="120" />
              <el-table-column
                prop="content"
                label="操作内容"
                min-width="160"
                show-overflow-tooltip
              />
              <el-table-column prop="approver" label="实际审批人" min-width="120" />
              <el-table-column prop="process_time" label="处理时间" min-width="140" />
              <el-table-column prop="processed" label="处理状态" width="100" align="center" />
              <el-table-column label="操作" width="120" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button
                    type="danger"
                    v-if="row.processed === '未处理'"
                    link
                    @click="handleRevoke(row)"
                    >撤销</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="table-pagination">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="initiatedPage"
                :page-size="initiatedPageSize"
                :total="initiatedTotal"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="onInitiatedSizeChange"
                @current-change="onInitiatedPageChange"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>我的待办</span>
              </div>
            </template>
            <el-table :data="pagedMyTodo" size="small" height="400">
              <el-table-column prop="user_name" label="操作人" min-width="120" />
              <el-table-column prop="operate" label="操作类型" min-width="120" />
              <el-table-column prop="create_time" label="创建时间" min-width="140" />
              <el-table-column
                prop="content"
                label="操作内容"
                min-width="160"
                show-overflow-tooltip
              />
              <el-table-column prop="approver" label="实际审批人" min-width="120" />
              <el-table-column prop="process_time" label="处理时间" min-width="140" />
              <el-table-column prop="processed" label="处理状态" width="100" align="center" />
              <el-table-column label="操作" width="120" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    v-if="row.processed === '未处理'"
                    link
                    @click="handleReview(row)"
                    >审核</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="table-pagination">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="todoPage"
                :page-size="todoPageSize"
                :total="todoTotal"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="onTodoSizeChange"
                @current-change="onTodoPageChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="ops-stats">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>运营数据统计</span>
          </div>
        </template>
        <div class="ops-channels">
          <el-row :gutter="16">
            <el-col :span="3">
              <el-card class="ops-summary" shadow="hover" :body-style="{ padding: '14px 16px' }">
                <div class="channel-card">
                  <div class="channel-title">总计</div>
                  <div class="channel-values">
                    <div class="label">人民币总额</div>
                    <div class="value">{{ formatCurrencyCny(opsTotal.amountCny) }}</div>
                  </div>
                  <div class="channel-values">
                    <div class="label">美元总额</div>
                    <div class="value">{{ formatCurrencyUsd(opsTotal.amountUsd) }}</div>
                  </div>
                  <div class="channel-values">
                    <div class="label">单数</div>
                    <div class="value">{{ formatInteger(opsTotal.count) }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col v-for="ch in opsChannels" :key="ch.key" :span="3">
              <el-card shadow="hover" :body-style="{ padding: '14px 16px' }">
                <div class="channel-card">
                  <div class="channel-title">{{ ch.name }}</div>
                  <div class="channel-values">
                    <div class="label">人民币</div>
                    <div class="value">{{ formatCurrencyCny(ch.amountCny) }}</div>
                  </div>
                  <div class="channel-values">
                    <div class="label">美元</div>
                    <div class="value">{{ formatCurrencyUsd(ch.amountUsd) }}</div>
                  </div>
                  <div class="channel-values">
                    <div class="label">单数</div>
                    <div class="value">{{ formatInteger(ch.count) }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import request from '@/axios'

const countTab = ref<'yesterday' | 'month'>('yesterday')
const amountTab = ref<'yesterday' | 'month'>('yesterday')

const countRanking = ref<{
  yesterday: Array<{ name: string; orders: number; percent: string | number }>
  month: Array<{ name: string; orders: number; percent: string | number }>
}>({
  yesterday: [],
  month: []
})

const amountRanking = ref<{
  yesterday: Array<{ name: string; amountUsd: number; amountCny: number; percent: string | number }>
  month: Array<{ name: string; amountUsd: number; amountCny: number; percent: string | number }>
}>({
  yesterday: [],
  month: []
})

type Period = 'yesterday' | 'month'
const periodToParam: Record<Period, number> = { yesterday: 1, month: 10 }

async function fetchOrderRanking(period: Period) {
  const res = await request.get<{ amount: any; quantity: any }>({
    url: '/admin/index/order_ranking',
    params: { time_period: periodToParam[period] }
  })
  const payload: any = (res as any)?.data ? (res as any).data : res
  // 订单数排行榜
  const quantityList = (payload?.quantity?.list || []).map((item: any) => ({
    name: item.name || '未命名',
    orders: Number(item.amount) || 0,
    percent:
      typeof item.percent === 'string' && item.percent.includes('%')
        ? item.percent
        : `${Number(item.percent) || 0}%`
  }))
  // 订单金额排行榜（优先人民币）
  const amountList = (payload?.amount?.list || []).map((item: any) => ({
    name: item.name || '未命名',
    amountUsd: Number(item.amount_usd) || 0,
    amountCny: Number(item.amount_cny) || 0,
    percent:
      typeof item.percent === 'string' && item.percent.includes('%')
        ? item.percent
        : `${Number(item.percent) || 0}%`
  }))

  // 设置对应 period 的数据
  countRanking.value = {
    ...countRanking.value,
    [period]: quantityList
  }
  amountRanking.value = {
    ...amountRanking.value,
    [period]: amountList
  }
}

async function fetchQuantityRanking(period: Period) {
  const res = await request.get<{ quantity: any }>({
    url: '/admin/index/order_ranking',
    params: { time_period: periodToParam[period] }
  })
  const payload: any = (res as any)?.data ? (res as any).data : res
  const quantityList = (payload?.quantity?.list || []).map((item: any) => ({
    name: item.name || '未命名',
    orders: Number(item.amount) || 0,
    percent:
      typeof item.percent === 'string' && item.percent.includes('%')
        ? item.percent
        : `${Number(item.percent) || 0}%`
  }))
  countRanking.value = { ...countRanking.value, [period]: quantityList }
}

async function fetchAmountRanking(period: Period) {
  const res = await request.get<{ amount: any }>({
    url: '/admin/index/order_ranking',
    params: { time_period: periodToParam[period] }
  })
  const payload: any = (res as any)?.data ? (res as any).data : res
  const amountList = (payload?.amount?.list || []).map((item: any) => ({
    name: item.name || '未命名',
    amountUsd: Number(item.amount_usd) || 0,
    amountCny: Number(item.amount_cny) || 0,
    percent:
      typeof item.percent === 'string' && item.percent.includes('%')
        ? item.percent
        : `${Number(item.percent) || 0}%`
  }))
  amountRanking.value = { ...amountRanking.value, [period]: amountList }
}

onMounted(async () => {
  // 初始化：若两个榜单周期一致，合并为一次请求；否则分别请求
  if (countTab.value === amountTab.value) {
    await fetchOrderRanking(countTab.value)
  } else {
    await Promise.all([fetchQuantityRanking(countTab.value), fetchAmountRanking(amountTab.value)])
  }
  await Promise.all([fetchMyInitiated(), fetchMyTodo(), fetchOrderStatistics()])
})

watch(countTab, (val) => {
  fetchQuantityRanking(val)
})

watch(amountTab, (val) => {
  fetchAmountRanking(val)
})

function formatCurrencyCny(value: number) {
  return `¥ ${Math.round(value).toLocaleString()}`
}

function formatCurrencyUsd(value: number) {
  return `$ ${Math.round(value).toLocaleString()}`
}

// 兼容金额排行榜原有调用，默认按人民币格式化
function formatCurrency(value: number) {
  return formatCurrencyCny(value)
}

function formatInteger(value: number) {
  return value.toLocaleString()
}

// 我的发起：服务端分页
const initiatedPage = ref(1)
const initiatedPageSize = ref(10)
const initiatedTotal = ref(0)
const myInitiated = ref<
  Array<{
    id: number
    user_id: number | string
    operate: string
    content: string
    approver: string
    processed: string | number
    process_time: string
    create_time: string
    entity_id?: number
    child_entity_id?: number
  }>
>([])

const fetchMyInitiated = async () => {
  const res = await request.get<{ list: any[]; total: number }>({
    url: '/admin/index/initiated',
    params: { pageIndex: initiatedPage.value, pageSize: initiatedPageSize.value }
  })
  const list = (res.data?.list || []).map((item: any) => ({
    id: item.id,
    user_id: item.user_id,
    operate: item.operate,
    content: item.content,
    approver: item.approver,
    processed: item.processed,
    process_time: item.process_time,
    create_time: item.create_time,
    entity_id: item.entity_id,
    child_entity_id: item.child_entity_id
  }))
  myInitiated.value = list
  initiatedTotal.value = Number(res.data?.total || 0)
}

// 我的待办：服务端分页
const todoPage = ref(1)
const todoPageSize = ref(10)
const todoTotal = ref(0)
const myTodo = ref<
  Array<{
    id: number
    user_id: number | string
    user_name: string
    operate: string
    create_time: string
    content: string
    approver: string
    process_time: string
    processed: string | number
    entity_id?: number
    child_entity_id?: number
  }>
>([])

const router = useRouter()

async function reviewTodo(row: any) {
  try {
    const check = await request.get<{ result: boolean }>({
      url: `/admin/index/initiated_processed_result/${row.id}`
    })
    const payload: any = (check as any)?.data ? (check as any).data : check
    const alreadyProcessed = Boolean(payload?.result === true)
    if (alreadyProcessed) {
      ElMessageBox.alert('该条目已处理', '提示', { type: 'info' })
      return
    }
    const target = buildReviewRoute(row)
    if (!target) {
      ElMessage.warning('无法识别操作类型，暂不支持跳转')
      return
    }
    router.push(target)
  } catch (e) {
    ElMessage.error('审核跳转失败')
  }
}

function buildReviewRoute(row: any): string | undefined {
  const id = row.entity_id
  if (!id) {
    ElMessage.warning('id为空')
    return
  }
  switch (row.operate) {
    case '订单-编辑':
      return `/order/order-management/audit?id=${id}`
    case '订单-部分发货申请发起':
      return `/order/order-management/detail?id=${id}&tab=related_products`
    case '订单-支付凭证上传':
      return `/order/order-management/detail?id=${id}&tab=receipt_management`
    case '退货退款单-创建':
      return `/orderReturn-management/orderReturn`
    case '发票-创建':
      return `/order/invoice-management/detail?id=${id}`
    case '采购付款单-创建':
      return `/purchase/payment-order-management`
    case '库存-调拨取消':
      return `/warehouse/allot-management`
    case '库存-校对发起':
      return `/warehouse/inventory-management/checking?id=${id}`
    default:
      return undefined
  }
}

function revokeTodo(row: any) {
  const target = buildReviewRoute(row)
  if (!target) {
    ElMessage.warning('无法识别操作类型，暂不支持跳转')
    return
  }
  router.push(target)
}

const fetchMyTodo = async () => {
  const res = await request.get<{ list: any[]; total: number }>({
    url: '/admin/index/to_do',
    params: { pageIndex: todoPage.value, pageSize: todoPageSize.value }
  })
  const list = (res.data?.list || []).map((item: any) => ({
    id: item.id,
    user_id: item.user_id,
    user_name: item.user_name,
    operate: item.operate,
    create_time: item.create_time,
    content: item.content,
    approver: item.approver,
    process_time: item.process_time,
    processed: item.processed,
    entity_id: item.entity_id,
    child_entity_id: item.child_entity_id
  }))
  myTodo.value = list
  todoTotal.value = Number(res.data?.total || 0)
}

function handleRevoke(row: any) {
  revokeTodo(row)
}

function handleReview(row: any) {
  reviewTodo(row)
}

// 分页：我的发起
const pagedMyInitiated = computed(() => myInitiated.value)
function onInitiatedSizeChange(size: number) {
  initiatedPageSize.value = size
  initiatedPage.value = 1
  fetchMyInitiated()
}
function onInitiatedPageChange(page: number) {
  initiatedPage.value = page
  fetchMyInitiated()
}

// 分页：我的待办
const pagedMyTodo = computed(() => myTodo.value)
function onTodoSizeChange(size: number) {
  todoPageSize.value = size
  todoPage.value = 1
  fetchMyTodo()
}
function onTodoPageChange(page: number) {
  todoPage.value = page
  fetchMyTodo()
}

// 运营数据统计
const opsTotal = ref<{ amountCny: number; amountUsd: number; count: number }>({
  amountCny: 0,
  amountUsd: 0,
  count: 0
})

const opsChannels = ref<
  Array<{ key: string; name: string; amountCny: number; amountUsd: number; count: number }>
>([])

async function fetchOrderStatistics() {
  const res = await request.get<
    Array<{ usd_total_amount: number; cny_total_amount: number; total_qty: number; source: string }>
  >({
    url: '/admin/index/order_statistics'
  })
  const list = (res.data || []).map((item: any, index: number) => ({
    key: String(index),
    name: item.source,
    amountCny: Number(item.cny_total_amount) || 0,
    amountUsd: Number(item.usd_total_amount) || 0,
    count: Number(item.total_qty) || 0
  }))
  opsChannels.value = list
  const sumCny = list.reduce((s, i) => s + i.amountCny, 0)
  const sumUsd = list.reduce((s, i) => s + i.amountUsd, 0)
  const sumQty = list.reduce((s, i) => s + i.count, 0)
  opsTotal.value = {
    amountCny: Math.round(sumCny),
    amountUsd: Math.round(sumUsd),
    count: Math.round(sumQty)
  }
}
</script>
<style lang="less" scoped>
.home {
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  .home-bg {
    width: 10%;
    max-width: 1200px;
    margin-bottom: 20px;
  }
}

.leaderboards {
  padding: 0 20px 20px;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .card-tabs {
    margin-left: 12px;
  }
}

.todos {
  padding: 0 20px 20px;

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.ops-stats {
  padding: 0 20px 24px;

  .ops-summary {
    margin-bottom: 16px;
    background: linear-gradient(120deg, #eef2ff 0%, #e0e7ff 100%);
    border: none;
  }

  .summary-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .summary-title {
    font-weight: 600;
    color: #1f2937;
  }

  .summary-values {
    display: flex;
    gap: 24px;
  }

  .summary-item .label,
  .channel-values .label {
    font-size: 12px;
    color: #6b7280;
  }

  .summary-item .value,
  .channel-values .value {
    font-weight: 700;
    color: #111827;
  }

  .ops-channels .el-col {
    margin-bottom: 16px;
  }

  .channel-title {
    margin-bottom: 6px;
    font-weight: 600;
    color: #374151;
  }
}
</style>
